Problem Statement ¶
With Yii Framework 2.0, one of the many changes, that Yii 1.x developers will face is removal of all client helpers and revamp of the CClientScript
functionality. For example no more CHtml::ajaxLink
or Html::ajaxLink
. How do you cater to such requirements in Yii 2.0?
Reasoning ¶
One of the critical changes in Yii 2 framework design that you will notice versus Yii 1.x, is that Yii 2 focuses on moving the entire presentational layer to a new View
object. With this change, the Yii 2 team has also eliminated most of the client related functionality embedded in PHP classes from the core framework. Thus it has made the code cleaner to use. Hence, helpers like ajaxLink
are no more available. This helps you manage your client assets better, improves performance, and control them better.
Solution ¶
You can easily create and combine all such client helpers for your need into separate JS files. Use the new AssetBundle and AssetManager functionality with the View object in Yii2, to manage these assets and how they are loaded.
Alternatively, inline assets (JS/CSS) can be registered at runtime from within the View
.
For example you can clearly simulate the ajaxLink feature using a inline javascript. Its however recommended if you can merge where possible, client code (JS/CSS) into separate JS/CSS files and loaded through the AssetBundle. Note there is no more need of a CClientScript anymore:
$script = <<< JS
$('#el').on('click', function(e) {
$.ajax({
url: '/path/to/action',
data: {id: '<id>', 'other': '<other>'},
success: function(data) {
// process data
}
});
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
For javascript IDE support
Supposing you want to use a jquery plugin in your view, you can:
$jsView = file_get_contents(Yii::getAlias('@webroot/js/myfile.js')); $this->registerJs($jsView, View::POS_END);
$contrAction = Yii::$app->urlManager->parseRequest(Yii::$app->request)[0]; $contrAction = str_replace("/", "_", $contrAction); $jsView = file_get_contents(Yii::getAlias('@webroot/js/'.$contrAction.".js"));
Capture JS or CSS inside a view withoud loosing code color highlighting.
I build a simple component to capture JS or CSS inside a view without loosing code color highlighting.
https://gist.github.com/MGHollander/d438691179466f983a2a
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.